//
//  LetterDetailViewController.m
//  Growth
//
//  Created by Hobo.Chen on 3/29/12.
//  Copyright (c) 2012 MEETStudio. All rights reserved.
//

#import "LetterDetailViewController.h"

#import "CJSONScanner.h"
#import "CJSONSerializer.h"


#define CACHEURL @"cacheUrl"

static ASIHTTPConnection *chat_history_connect;
static ASIHTTPConnection *chat_new_connect;
static ASIHTTPConnection *chat_send_connect;


@interface LetterDetailViewController (){
    
}

@end

@implementation LetterDetailViewController

@synthesize familyDict;

@synthesize myTableView;

@synthesize chatHistoryArray;
@synthesize chatNewArray;

@synthesize fid;

@synthesize threadID;

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
 self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
 if (self) {
 // Custom initialization.
 }
 return self;
 }
 */

- (id)initWithDict:(NSDictionary *)dict{
    
    if (self = [super init]) {
        
        
        self.familyDict = dict;
     }
    return self;
    
}

- (id)initWithThreadId:(NSString *)threadid{
    
    if (self = [super init]) {
        
        
        self.threadID = threadid;
    }
    return self;
    
}

- (id)initWithTitle:(NSString *)title fid:(NSString *)freindId{
    
    if (self = [super init]) {
        
        self.fid = [freindId retain];
        self.title = title;
    }
    return self;
   
    
}





- (id)initWithTitle:(NSString *)title{
    
    if (self = [super init]) {
        self.title = title;
    }
    return self;
    
    
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    
    [self.view setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
    //background
    NSString *file = [[NSBundle mainBundle] pathForResource:@"bg_family_iPhone.png" ofType:nil];
    UIImage *image = [UIImage imageWithContentsOfFile:file];
    self.view.layer.contents = (id) image.CGImage;
  
    
    [self initGrowingTextView ];
    
    //iOS 5.0 Top bar效果优化
    double sysVersion = [[[UIDevice currentDevice] systemVersion] doubleValue];
    if (sysVersion >= 5.0) {
        
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"BTbg_iPhone" ofType:@"png"];
        
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithContentsOfFile:filePath] forBarMetrics:UIBarMetricsDefault];
        
    }
    else{
        
        [self.navigationController.navigationBar setTintColor:[UIColor colorWithRed:51.0/255.0 green:102.0/255.0 blue:153.0/255.0 alpha:1]];
        
    }

    	
	//table 下拉刷新
	if (_refreshHeaderView == nil) {
		
		_refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - myTableView.bounds.size.height, self.view.frame.size.width, myTableView.bounds.size.height)];
		_refreshHeaderView.delegate = self;
        _refreshHeaderView.backGroundImageView.hidden = YES;
		[myTableView addSubview:_refreshHeaderView];
			
	}
	
	//  update the last update date
	[_refreshHeaderView refreshLastUpdatedDate];
    
      
    if(self){
		[[NSNotificationCenter defaultCenter] addObserver:self 
												 selector:@selector(keyboardWillShow:) 
													 name:UIKeyboardWillShowNotification 
												   object:nil];
		
		[[NSNotificationCenter defaultCenter] addObserver:self 
												 selector:@selector(keyboardWillHide:) 
													 name:UIKeyboardWillHideNotification 
												   object:nil];		
	}

     pageNo = 1;
    
  
    
    [self loadData];
    
    
    [super viewDidLoad];
}

- (void)backAction:(id)sender{
    
    if ([self.navigationController.navigationBar viewWithTag:3]) {
        
        [[self.navigationController.navigationBar viewWithTag:3] setHidden:NO];
    }
    
    if (self.navigationController.viewControllers.count > 1) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    else{
        
         [self dismissModalViewControllerAnimated:YES];
    }
    

    
}


- (void)navTopbarSetup
{
    self.title = @"家庭讨论圈";
    //定义左侧按钮
    
    UIButton *leftButton1 = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
    [leftButton1 setImage:[UIImage imageNamed:@"icon3_family_iPhone.png"] forState:UIControlStateNormal];
    [leftButton1 addTarget:self action:@selector(flipToBack:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithCustomView:leftButton1];
    self.navigationItem.leftBarButtonItem = leftButton;
    [leftButton1 release];
    [leftButton release];
    
 

    
    //iOS 5.0 Top bar效果优化
    double sysVersion = [[[UIDevice currentDevice] systemVersion] doubleValue];
    if (sysVersion >= 5.0) {
        
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"BTbg_iPhone" ofType:@"png"];
        
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithContentsOfFile:filePath] forBarMetrics:UIBarMetricsDefault];
        
    }
    else{
        
        [self.navigationController.navigationBar setTintColor:[UIColor colorWithRed:51.0/255.0 green:102.0/255.0 blue:153.0/255.0 alpha:1]];
        
    }
    
}


- (void)loadData{
    
    if (self.threadID != nil) {
        [self loadLetterList];
    }
    
}



- (void)loadLetterList{
    
    
    NSString *userName = [[NSUserDefaults standardUserDefaults] valueForKey:USER_NAME];
    NSString *UserID = [[NSUserDefaults standardUserDefaults] valueForKey:USER_ID];
    
    NSString *urlString = [NSString stringWithFormat:@"%@/MobileMicroBlog/%@/ShowMessage.aspx?UserID=%@&threadID=%@",BASEURL,userName,UserID,self.threadID];
	NSURL *url = [NSURL URLWithString:urlString];
    
    if (chat_history_connect != nil) {
        
        [chat_history_connect release];
        chat_history_connect = nil;
    }
    
    chat_history_connect = [[ASIHTTPConnection alloc] initGETWithURL:url resultDict:YES isCache:YES];
    chat_history_connect.connectionDelegate = self;
    
    [chat_history_connect startAsynchronous];

    
    
}


- (void)viewWillAppear:(BOOL)animated{
    
    CLog(@"LetterDetailView will appear");
    [super viewWillAppear:NO];
}


- (void)refreshView
{
    NSInteger count = [chatHistoryArray count];
        
    //底部刷新条
    if ( _refreshTailView == nil) {
        
        _refreshTailView = [[EGORefreshTableTailView alloc] initWithFrame:CGRectMake(0.0f, self.myTableView.contentSize.height, 320, self.myTableView.frame.size.height)];
        _refreshTailView.delegate = self;
        [self.myTableView addSubview:_refreshTailView];
        _refreshTailView.backGroundImageView.hidden = YES;
        
    }
    
    if (_refreshTailView != nil) {
        float height = MAX(self.myTableView.contentSize.height, self.myTableView.frame.size.height); 
        [_refreshTailView setFrame:CGRectMake(0.0f, height, 320, self.myTableView.frame.size.height)];
    }
    
    
}


#pragma mark  Load Data

- (void)reloadChatData{
    
    [self.chatHistoryArray removeAllObjects];
    [self.chatNewArray removeAllObjects];
    pageNo = 1;
    refTimePoint = 0;
    [self loadChactHistory];
    
    
}

- (void)loadChactHistory{
       
    [LoadingView showDefaultLoadingView];

    //时间点
    if (pageNo ==1) {
        
        NSDate *zoneDate = [NSDate date];
        NSTimeZone *zone = [NSTimeZone defaultTimeZone];//获得当前应用程序默认的时区
        NSInteger interval = [zone secondsFromGMTForDate:zoneDate];//以秒为单位返回当前应用程序与世界标准时间（格林威尼时间）的时差
        NSDate *date=[NSDate dateWithTimeIntervalSinceNow:interval];
        
        NSTimeInterval _interval = [date timeIntervalSince1970];
        refTimePoint = (long long int)(_interval -interval +VERIFY_LOCALE_DATE_INTERVAL)*1000; 

    }
    
    NSString *urlString = @" ";
	NSURL *url = [NSURL URLWithString:urlString];
    
    BOOL isCache = NO;
    if (pageNo == 1) {
        isCache = YES;
        
    }
    
    if (chat_history_connect != nil) {
        chat_history_connect.connectionDelegate = nil;
        [chat_history_connect release];
    }

    chat_history_connect = [[ASIHTTPConnection alloc] initGETWithURL:url resultDict:NO isCache:isCache];
    chat_history_connect.connectionDelegate = self;
    [chat_history_connect startAsynchronous];
    
//    [connectionArray addObject:connection];
//   [connection release];
    
    
    
}


- (IBAction)chatSend:(id)sender{
    
    NSString *userName = [[NSUserDefaults standardUserDefaults] valueForKey:USER_NAME];
    
    NSString *urlString = [NSString stringWithFormat:@"%@/MobileMicroBlog/%@/CreateMessage.aspx",BASEURL,userName];
    
    
    NSArray *keys = [NSArray arrayWithObjects:@"Body",@"Receiver",@"Sender", nil];
    
    NSArray *objects = [NSArray arrayWithObjects:textView.text,self.title,userName, nil];
    

    NSURL *url = [NSURL URLWithString:urlString];
    
    
    NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
    
    NSString *bodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
    CLog(@"theBodyString  %@", bodyString);
    
    //  //
    NSData *_jsonData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
    
    if (chat_send_connect != nil) {
        chat_send_connect.connectionDelegate = nil;
        [chat_send_connect release];
        chat_send_connect = nil;
    }
    
    chat_send_connect = [[ASIHTTPConnection alloc]initPOSTWithURL:url jsonData:_jsonData resultDict:YES
                         ];
    chat_send_connect.connectionDelegate = self;
    [chat_send_connect startAsynchronous];
    
}

#pragma mark - 
#pragma mark - Connection Delegate
- (void)requestFinished:(ASIHTTPConnection *)connection resultDict:(NSDictionary *)dict URL:(NSURL *)url info:(NSDictionary *)info{

    
    [LoadingView hideWithAnimated:YES];
    [self doneLoadingTableViewData];
    
    NSString *urlStr = [url absoluteString];
    NSRange range ;
      
    range = [urlStr rangeOfString:@"/chat/history"];
    if (range.length > 0) {
        
        if (chatHistoryArray == nil) {
            NSMutableArray *tempArray = [[NSMutableArray alloc]init];
            self.chatHistoryArray = tempArray;
            [tempArray release];
        }
        
        if (pageNo == 1) {
            [self.chatHistoryArray removeAllObjects];
            
            [[NSUserDefaults standardUserDefaults] setValue:urlStr forKey:CACHEURL];
        }
        
              
        BOOL isChache = [connection.request didUseCachedResponse];
        //在不是缓存数据的情况下清楚缓存，第一页缓存和最新日志缓存
        if (!isChache) {
            
            NSString *timePointStr = [[NSUserDefaults standardUserDefaults] valueForKey:@"chatTimePoint"];
            if (timePointStr != nil) {
                long long int timePoint = [timePointStr longLongValue];
                
                            
                //第一页缓存
                 NSString *urlString = [NSString stringWithFormat:@"%@/mobile/family/chat/history?familyId=%@&timePoint=%lld&pageNo=%d&pageSize=%d",BASEURL, @"",timePoint,1,20];
                
                NSURL *cacheUrl = [NSURL URLWithString:urlString];
                [[ASIDownloadCache sharedCache] removeCachedDataForURL:cacheUrl];
                
               
            }
            
        }

        
        
        
        NSMutableArray *otherArray =[dict objectForKey:@"object"];
        
        if (otherArray != nil && otherArray.count > 0) {
            
            [self.chatHistoryArray addObjectsFromArray:otherArray];
            
            [myTableView reloadData];
            
            [self refreshView];
            
            if (pageNo == 1) {
                
                  [myTableView scrollRectToVisible:CGRectMake(0, self.myTableView.contentSize.height-100, 320, 100) animated:YES]; 
            }
        
        }
        
        if (chatHistoryArray.count == 0 && chatNewArray.count == 0 && [self.title isEqualToString:@"家庭讨论圈"]) {
            
                 [[self.view viewWithTag:123] removeFromSuperview];
            
                UILabel *tipLable = [[UILabel alloc] initWithFrame:CGRectMake(10, 150, 300, 30)];
                tipLable.backgroundColor = [UIColor clearColor];
                tipLable.textColor = [UIColor grayColor];
                tipLable.textAlignment = UITextAlignmentCenter;
                tipLable.font = [UIFont systemFontOfSize:14];
                tipLable.tag = 123;
                tipLable.text = @"当前没有任何信息哟~~";
                [self.view addSubview:tipLable];
                [tipLable release];
                    

        }
        else{
            [[self.view viewWithTag:123] removeFromSuperview];
        }
        
              
        [self doneLoadingTableViewData];
        
    }
    
   
    range = [urlStr rangeOfString:@"ShowMessage"];
    if (range.length > 0) {
        
        if (chatHistoryArray == nil) {
            chatHistoryArray = [[NSMutableArray alloc]init];
        }
        
        [chatHistoryArray removeAllObjects];
        [chatHistoryArray addObject:dict];
        
        NSArray * array = [dict objectForKey:@"Replies"];
        if (array != nil && array.count > 0) {
            [chatHistoryArray addObjectsFromArray:array];
        }
        [self.myTableView reloadData];
        [self refreshView];
        
        
    }
    
    
    
    range = [urlStr rangeOfString:@"CreateMessage.aspx"];
    if (range.length > 0) {
                     //发送成功
             pageNo = 1;
        if (self.threadID == nil) {
            [self.navigationController popViewControllerAnimated:YES];
            [LoadingView showDurationMessageLoadingViewWith:2 message:@"私信发送成功"];
        }
     }
    
    
    //私信列表
    range = [urlStr rangeOfString:@"letter/list"];
    if (range.length > 0) {
        
        NSArray *array = [dict objectForKey:@"result"];
    
        if (array != nil && array.count > 0) {
            
            if (chatHistoryArray == nil) {
                chatHistoryArray = [[NSMutableArray alloc] init];
            }
            else{
                [chatHistoryArray removeAllObjects];
            }
            [self.chatHistoryArray addObjectsFromArray:array];
            
            [myTableView reloadData];
            [self doneLoadingTableViewData];
            
            [self refreshView];
            
            if (pageNo == 1) {
                
                [myTableView scrollRectToVisible:CGRectMake(0, self.myTableView.contentSize.height-100, 320, 100) animated:YES];
            }
            
        }

        
    }
    
    
    //
    range = [urlStr rangeOfString:@"letter/send"];
    if (range.length > 0) {
        //发送成功
        CLog(@"私信发送成功，返回数据：%@",dict);
        pageNo = 1;
        [self loadLetterList];
    }
    

    
    
}

- (void)requestFailed:(ASIHTTPConnection *)connection error:(NSError *)error URL:(NSURL *)url info:(NSDictionary *)info{
    
    
}



#pragma mark UITableViewDataSource


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
	
	return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
	
	//return 100;
    return self.chatHistoryArray.count;
    
}




- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
	
	NSInteger row = [indexPath row];
    static NSString *MyIdentifier = @"LetterDetailCell";
	// Try to retrieve from the table view a now-unused cell with the given identifier.
	LetterDetailCell *cell =(LetterDetailCell *) [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
	
    if (cell == nil) {
		NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"LetterDetailCell" 
                                                     owner:self options:nil];
#ifdef __IPHONE_2_1
		cell = (LetterDetailCell *)[nib objectAtIndex:0];
#else
		cell = (LetterDetailCell *)[nib objectAtIndex:1];
#endif
        
      //  [cell.iconButton addTarget:self action:@selector(toUserView:) forControlEvents:UIControlEventTouchUpInside];
        cell.backgroundColor = [UIColor clearColor];
        
	}
    
	cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
   
    NSDictionary *dict = [chatHistoryArray objectAtIndex:indexPath.row];
    [cell loadCellWith:dict];
       
    return cell;
	
	
}



- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
	
	
	return nil;
}


#pragma mark UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
	
	
	UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
	return cell.frame.size.height;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [textView resignFirstResponder];
   //  [self.inputVIew setFrame:CGRectMake(0, 420, 320, 40)];
    
}

#pragma mark button action




#pragma mark -
#pragma mark Table 下拉刷新
#pragma mark -
#pragma mark Data Source Loading / Reloading Methods

- (void)reloadTableViewDataSource{
	
	//  should be calling your tableviews data source model to reload
    
	//  put here just for demo
    
    _reloading = YES;
    _TailReloading = YES;
    
    if (self.myTableView.contentOffset.y > 100) {//上拉
     
        pageNo = 1;
        
        if ([self.title isEqualToString:@"家庭讨论圈"]) {
            
            [self loadChactHistory];
        }
        else{
            
            [self loadLetterList];
        }

        _reloading = YES;
          
    }
    else{//下拉刷新
        
      
            pageNo ++;
            if ([self.title isEqualToString:@"家庭讨论圈"]) {
                
                [self loadChactHistory];
            }
            else{
                
                [self loadLetterList];
            }

      
               
    }
     
	
}

- (void)doneLoadingTableViewData{
	
	//  model should call this when its done loading
	_reloading = NO;
	[_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.myTableView];
	_TailReloading = NO;
    [_refreshTailView egoRefreshScrollViewDataSourceDidFinishedLoading:self.myTableView];
}



#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{	
	
	[_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];

    [_refreshTailView egoRefreshScrollViewDidScroll:scrollView];

	
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	
	[_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
	[_refreshTailView egoRefreshScrollViewDidEndDragging:scrollView];
}


#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
	
	[self reloadTableViewDataSource];
	//[self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:1.6];
	
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
	
	return _reloading; // should return if data source model is reloading
	
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
	
	return [NSDate date]; // should return date data source was last changed
	
}


#pragma mark - EGORefreshTableTailDelegate
- (void)egoRefreshTableTailDidTriggerRefresh:(EGORefreshTableTailView*)view
{
    [self reloadTableViewDataSource];
    //[self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:1];

}
- (BOOL)egoRefreshTableTailDataSourceIsLoading:(EGORefreshTableTailView*)view
{
    // CLog(@"_TailReloading  %d", _TailReloading);
    return _TailReloading;
}

- (NSDate*)egoRefreshTableTailDataSourceLastUpdated:(EGORefreshTableTailView*)view
{
    return [NSDate date]; // should return date data source was last changed
}




/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations.
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    
    if (chat_history_connect != nil) {
        chat_history_connect.connectionDelegate = nil;
        [chat_history_connect release];
        chat_history_connect = nil;
    }
    
    if (chat_new_connect != nil) {
        chat_new_connect.connectionDelegate = nil;
        [chat_new_connect release];
        chat_new_connect = nil;
    }
    
    if (chat_send_connect != nil) {
        chat_send_connect.connectionDelegate = nil;
        [chat_send_connect release];
        chat_send_connect = nil;
    }
    
     
    [chatNewArray release];
    [chatHistoryArray release];
    
    [familyDict release];
    
    [containerView release];
    [textView release];
    
    [myTableView release];
    
    [super dealloc];
}


-(IBAction)backGroundTap:(id)sender{
    
    [textView resignFirstResponder];
    //[self.inputVIew setFrame:CGRectMake(0, 420, 320, 40)];
    
}


#pragma mark--
#pragma  mark GroingTextView methord

- (void)initGrowingTextView{
    
    containerView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height -50, 320, 50)];
    //
    containerView.backgroundColor = [UIColor redColor];
    
    
	textView = [[HPGrowingTextView alloc] initWithFrame:CGRectMake(5, 10, 248, 50)];
    textView.contentInset = UIEdgeInsetsMake(0, 5, 0, 5);
    
	textView.minNumberOfLines = 1;
	textView.maxNumberOfLines = 6;
	textView.returnKeyType = UIReturnKeyDefault; //just as an example
	textView.font = [UIFont systemFontOfSize:15.0f];
	textView.delegate = self;
    textView.internalTextView.scrollIndicatorInsets = UIEdgeInsetsMake(5, 0, 5, 0);
    
    
    textView.backgroundColor = [UIColor whiteColor];
    
    // textView.text = @"test\n\ntest";
	// textView.animateHeightChange = NO; //turns off animation
    
    
    [self.view insertSubview:containerView atIndex:100];
	
    UIImage *rawEntryBackground = [UIImage imageNamed:@"MessageEntryInputField.png"];
    UIImage *entryBackground = [rawEntryBackground stretchableImageWithLeftCapWidth:13 topCapHeight:22];
    UIImageView *entryImageView = [[[UIImageView alloc] initWithImage:entryBackground] autorelease];
    //entryImageView.frame = CGRectMake(5, 0, 248, 40);
    
    entryImageView.frame = CGRectMake(5, 0, 248, 50);
    entryImageView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    
    UIImage *rawBackground = [UIImage imageNamed:@"MessageEntryBackground.png"];
    UIImage *background = [rawBackground stretchableImageWithLeftCapWidth:13 topCapHeight:22];
    UIImageView *imageView = [[[UIImageView alloc] initWithImage:background] autorelease];
    imageView.frame = CGRectMake(0, 0, containerView.frame.size.width, containerView.frame.size.height);
    imageView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    
    textView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    
    // view hierachy
    [containerView addSubview:imageView];
    [containerView addSubview:textView];
    [containerView addSubview:entryImageView];
    
    //发送
    UIImage *sendBtnBackground = [[UIImage imageNamed:@"MessageEntrySendButton.png"] stretchableImageWithLeftCapWidth:13 topCapHeight:0];
    UIImage *selectedSendBtnBackground = [[UIImage imageNamed:@"MessageEntrySendButton.png"] stretchableImageWithLeftCapWidth:13 topCapHeight:0];
    
	UIButton *doneBtn = [UIButton buttonWithType:UIButtonTypeCustom];
	doneBtn.frame = CGRectMake(containerView.frame.size.width - 69, 12, 63, 27);
    doneBtn.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin;
	[doneBtn setTitle:@"发送" forState:UIControlStateNormal];
    
    [doneBtn setTitleShadowColor:[UIColor colorWithWhite:0 alpha:0.4] forState:UIControlStateNormal];
    doneBtn.titleLabel.shadowOffset = CGSizeMake (0.0, -1.0);
    doneBtn.titleLabel.font = [UIFont boldSystemFontOfSize:18.0f];
    
    [doneBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
	[doneBtn addTarget:self action:@selector(resignTextView) forControlEvents:UIControlEventTouchUpInside];
    [doneBtn setBackgroundImage:sendBtnBackground forState:UIControlStateNormal];
    [doneBtn setBackgroundImage:selectedSendBtnBackground forState:UIControlStateSelected];
	[containerView addSubview:doneBtn];
    
    
    containerView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    
    
}

-(void)resignTextView
{
    [self chatSend:nil];
     
    textView.text = @"";
    
	[textView resignFirstResponder];
    
}


- (IBAction)backGroundTap{
    
    [textView resignFirstResponder];
    textView.text = @"";
    
}


//Code from Brett Schumann
-(void) keyboardWillShow:(NSNotification *)note{
    // get keyboard size and loctaion
	CGRect keyboardBounds;
    backGoundButton.hidden = NO;
    [[note.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardBounds];
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    // Need to translate the bounds to account for rotation.
    keyboardBounds = [self.view convertRect:keyboardBounds toView:nil];
    
    [myTableView scrollRectToVisible:CGRectMake(0, self.myTableView.contentSize.height-10, 320, 10) animated:YES];
    
	// get a rect for the textView frame
	CGRect containerFrame = containerView.frame;
      
    containerFrame.origin.y = CGRectGetHeight(self.view.frame) - (keyboardBounds.size.height + containerFrame.size.height);
    
	// animations settings
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];
	
	// set views with new info
	containerView.frame = containerFrame;
	
    //tableView
    if (self.myTableView.contentSize.height>190) {
        CGRect tableFrame = self.myTableView.frame;
        tableFrame.origin.y =  - keyboardBounds.size.height ;
        [self.myTableView setFrame:tableFrame];
        
    }
      
	// commit animations
	[UIView commitAnimations];
    
    //backGround button
    
    backGoundButton.hidden = NO;
    backGoundButton.userInteractionEnabled = YES;
    [self.view bringSubviewToFront:backGoundButton];
    
}

-(void) keyboardWillHide:(NSNotification *)note{
    
    backGoundButton.hidden = YES;
    
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
	
	// get a rect for the textView frame
	CGRect containerFrame = containerView.frame;
    containerFrame.origin.y = CGRectGetHeight(self.view.frame) - containerFrame.size.height;
    
    // containerFrame.origin.y = 380;
	
	// animations settings
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];
    
	// set views with new info
	containerView.frame = containerFrame;
	
    //tableView
    CGRect tableFrame = self.myTableView.frame;
    tableFrame.origin.y = 0;
    [self.myTableView setFrame:tableFrame];

    
	// commit animations
	[UIView commitAnimations];
    
    //backGroundButton
    backGoundButton.hidden = YES;
    backGoundButton.userInteractionEnabled = NO;
   
}

- (void)growingTextView:(HPGrowingTextView *)growingTextView willChangeHeight:(float)height
{
    float diff = (growingTextView.frame.size.height - height);
    
	CGRect r = containerView.frame;
    r.size.height -= diff;
    r.origin.y += diff;
	containerView.frame = r;
}

-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    return YES;
}



@end
